/**
 *    title:  clientcore.c
 *    author:  sleeeeeping
 *    created:  2024-08-20 09:46:00
**/
#include <stdio.h>
#include <string.h>
#include <assert.h>

#include "tools.h"
#include "ftpclient.h"
#include "clientcore.h"

int _userLogin(FTPClient *ftp) {
    char username[32];
    printf("Name:");
    readName(username, sizeof(username));
    assert(userFtpClient(ftp, username) == 0);

    char password[32];
    printf("Password:");
    readPassword(password, sizeof(password), 1);
    assert(passFtpClient(ftp, password) == 0);

    return 0;
}

char* get_str(char* str,size_t size)
{
	size_t len = strlen(fgets(str,size,stdin));
	if('\n' == str[len-1])
		str[len-1] = '\0';
	else
		clear_stdin();

	return str;
}

void clientSysRun(int argc, const char *argv[]) {
    if (argc != 2) {
        puts("User:./client <ip>");
        return ;
    }
    FTPClient *ftp = createFtpClient(argv[1], 21);
    assert(ftp != NULL);
    assert(_userLogin(ftp) == 0);
    char cmd[CMD_LEN], arg[ARG_LEN];
    while (1) {
        printf("ftp>");
        scanf("%s", cmd);
        get_str(arg, sizeof(arg));
        
        size_t index = 0;
        while (index < cmdCnt) {
            if (strcmp(cmd, cmds[index].cmd)) {
                index += 1;
            } else break;
            if (index < cmdCnt) {
                cmds[index].func(ftp, arg);
            } else {
                feedbackView("未定义的命令!");
            }
        }
    }
}